package team.tunan.service.impl;

import net.sf.jsqlparser.expression.operators.relational.Matches;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import team.tunan.entity.Game;
import team.tunan.mapper.GameMapper;
import team.tunan.service.IGameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sqx
 * @since 2024-01-01
 */
@Service
public class GameServiceImpl extends ServiceImpl<GameMapper, Game> implements IGameService {
    @Autowired
    private GameMapper gameMapper;


    @Override
    public int doAdd(Game game) {
        int i = gameMapper.addGame(game);
        return i;
    }

    @Override
    public List<Map<String, Object>> getGameInfo(Integer isAll) {
        List<Map<String, Object>> gameInfo = gameMapper.getGameInfo(isAll);
        return gameInfo;
    }

    @Override
    public List<Map<String, Object>> getGameInfoTwo() {
        List<Map<String, Object>> gameInfo = gameMapper.getGameInfoTwo();
        return gameInfo;
    }

    @Override
    public Game getGame(Integer gid) {
        Game game = gameMapper.getGame(gid);
        return game;
    }

    @Override
    @Transactional
    public Map<String, Object> updateGame(Game game) {
        Map<String, Object> map = new HashMap<>();


        List<Matches> matches = gameMapper.haveMatches(game.getMatchId());
        Game mapperGame = gameMapper.getGame(game.getMatchId());
        if(mapperGame.getStatus() == 2){
            map.put("status", 2);//比赛已经结束
            map.put("flag", true);
            return map;
        }
        if(matches.size()>0 && game.getStatus() == 2){
            map.put("status", 0);//还有比赛场次没结束不能结束大比赛
            map.put("flag", true);
            return map;
        }
        if (game.getStatus() == 2&& mapperGame.getStatus() == 0){
            map.put("status", 1);//比赛还没开始不能直接结束
            map.put("flag", true);
            return map;
        }

        int i = gameMapper.updateGame(game);
        if(game.getStatus() == 2){
            gameMapper.endGame(game.getMatchId());
        }
        if(i>0){
            map.put("status", 3);//比赛成功开启
            map.put("flag", true);
            return map;
        }
        else{
            map.put("status", 4);//比赛开启失败
            map.put("flag", false);
            return map;
        }
    }
}
